package com.macro.mall.portal.service.impl;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.api.ResultCode;
import com.macro.mall.common.exception.Asserts;
import com.macro.mall.common.utils.Assist;
import com.macro.mall.mapper.*;
import com.macro.mall.model.*;
import com.macro.mall.portal.service.ExExamPapperService;
import com.macro.mall.portal.service.TiTrainingService;
import com.macro.mall.portal.service.UmsMemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * TiTraining的服务接口的实现类
 *
 * @author gaodx
 */
@Slf4j
@Service
public class TiTrainingServiceImpl implements TiTrainingService {

    private boolean isDebugEnabled = true;

    @Autowired
    private UmsMemberService memberService;
    @Autowired
    private MbrMemberScoreMapper mbrMemberScoreMapper;
    @Autowired
    private TiTrainingUserMapper tiTrainingUserMapper;
    @Autowired
    private TiTrainingSignRecordMapper tiTrainingSignRecordMapper;
    @Autowired
    private TiTrainingSignRecordLogMapper tiTrainingSignRecordLogMapper;
    @Autowired
    private TiTrainingMapper tiTrainingMapper;
    @Autowired
    private ExExamPapperService exExamPapperService;
    // TODO 当你看到这个方法时你应该创建一个工具类做通用的方法,定义自己的返回格式化

    @Override
    public List<TiTraining> find(String collegeId, Integer pageNum, Integer pageSize) {
        //TODO这里可以做通过Assist做添加查询
        PageHelper.startPage(pageNum, pageSize);
        Assist assist = new Assist();
        List<TiTraining> result = null;
        try {
            if (StrUtil.isNotEmpty(collegeId)) {
                assist.andEq("college_id ", collegeId);
            }
            result = tiTrainingMapper.selectTiTraining(assist);
            for (TiTraining one : result) {
                one.setThrough(exExamPapperService.isPassByTrainingId(one.getId()));
            }
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行获取TiTraining数据集-->结果:", result);
        }
        return result;
    }

    /**
     * 通过用户id，学院id过滤专题
     *
     * @param memberId 用户id
     * @param collegeId 学院id
     * @return
     */
    @Override
    public List<TiTraining> find(Long memberId, String collegeId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<TiTraining> result = null;
        try {
            Assist assist = new Assist();
            if (StrUtil.isNotEmpty(collegeId)) {
                assist.andEq("college_id ", collegeId);
            }
            //TODO  上线后开放
//            assist.setOrder(Assist.order("sort",false));
            assist.setOrder(Assist.order("create_time",false));

            result = tiTrainingMapper.selectTiTraining(assist);
            for (TiTraining one : result) {
                if ("0".equals(one.getUserAssign())) {
                    one.setCanSee("yes");
                } else {
                    for (TiTrainingUser user : one.getUserList()) {
                        if (user.getMemberId() == memberId.intValue()) {
                            one.setCanSee("yes");
                            break;
                        }
                    }
                }
                one.setThrough(exExamPapperService.isPassByTrainingId(one.getId()));
            }
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行获取TiTraining数据集-->结果:", result);
        }
        return result;
    }

    @Override
    public TiTraining findOne(Integer id) {
        if (id == null) {
            if (isDebugEnabled) {
                log.debug("执行通过TiTraining的id获得TiTraining对象-->失败:id不能为空");
            }
            Asserts.fail("执行通过TiTraining的id获得TiTraining对象-->失败:id不能为空");
        }
        TiTraining result = null;
        try {
            result = tiTrainingMapper.selectTiTrainingById(id);
            if(!StrUtil.isEmptyIfStr(result)&&!CollectionUtils.isEmpty(result.getSignList())){
                Date currentTime = new Date();
                result.getSignList().stream().forEach(r->{
                    UmsMember currentMember = memberService.getCurrentMember();
                    TiTrainingSignRecordLog srLog = new TiTrainingSignRecordLog();
                    srLog.setTrainingId(id);
                    srLog.setSignRecordId(r.getId());
                    srLog.setPhone(currentMember.getPhone());
                    TiTrainingSignRecordLog currentUserSignLog = tiTrainingSignRecordLogMapper.selectTiTrainingSignRecordLogSingle(srLog);
                    if (!StringUtils.isEmpty(currentUserSignLog)&&!StringUtils.isEmpty(currentUserSignLog.getSignStatus())) {
                        if ("01".equals(currentUserSignLog.getSignStatus())) {
                            r.setSignOutStatus("00");
                        }else
                        if ("02".equals(currentUserSignLog.getSignStatus())) {
                            r.setSignOutStatus("01");
                        }
                        r.setSignInStatus("01");
                    } else {
                        r.setSignInStatus("00");
                        r.setSignOutStatus("01");
                    }
                    if (!(r.getSignInStartTime().before(currentTime) && r.getSignInEndTime().after(currentTime))) {
                        r.setSignInStatus("01");
                    }
                    if (!(r.getSignOutStartTime().before(currentTime) && r.getSignOutEndTime().after(currentTime))) {
                        r.setSignOutStatus("01");
                    }
                });
            }
            if(!StrUtil.isEmptyIfStr(result)) {
                Integer avg = mbrMemberScoreMapper.selectAvgScoreTrainingObjSingle(id);
                result.setTrainingAvg(avg);
            }
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行通过TiTraining的id获得TiTraining对象-->结果:", result);
        }
        return result;
    }

    @Override
    public CommonResult saveNotNull(TiTraining value) {
        if (value == null) {
            if (isDebugEnabled) {
                log.debug("执行将TiTraining中属性值不为null的数据保存到数据库-->失败:对象不能为空");
            }
            Asserts.fail("失败:对象不能为空");
        }
        int result = 0;
        try {
            result = tiTrainingMapper.insertNotNullTiTraining(value);
            if (!CollectionUtils.isEmpty(value.getSignList())||!CollectionUtils.isEmpty(value.getUserList())) {
                if (value.getId()==null) {
                    TiTraining ttl = tiTrainingMapper.selectTiTrainingDescByObjSingle(value);
                    if (!StringUtils.isEmpty(ttl)){
                        value.setId(ttl.getId());
                    }
                }
                List<TiTrainingSignRecord> signList = value.getSignList();
                if (!CollectionUtils.isEmpty(signList)){
                    signList.stream().forEach(s->{
                        s.setTrainingId(value.getId());
                        s.setCreateTime(new Date());
                    });
                    tiTrainingSignRecordMapper.insertTiTrainingSignRecordByBatch(signList);
                }
                List<TiTrainingUser> userList = value.getUserList();
                if (!CollectionUtils.isEmpty(userList)){
                    userList.stream().forEach(s -> {
                        TiTrainingUser ttu = tiTrainingUserMapper.selectTiTrainingUserDescByObjSingle(s);
                        if (!StringUtils.isEmpty(ttu)){
                            s.setId(ttu.getId());
                            s.setTrainingId(value.getId());
                            s.setTrainingName(value.getName());
                            s.setUpdateTime(new Date());
                            tiTrainingUserMapper.updateNotNullTiTrainingUserById(s);
                        }
                    });
                }
            }
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行将TiTraining中属性值不为null的数据保存到数据库-->结果:", result);
        }
        return CommonResult.success(null);
    }

    @Override
    public CommonResult updateNotNullById(TiTraining value) {
        if (value == null) {
            if (isDebugEnabled) {
                log.debug("执行通过TiTraining的id更新TiTraining中属性不为null的数据-->失败:对象为null");
            }
            Asserts.fail("执行通过TiTraining的id更新TiTraining中属性不为null的数据-->失败:对象为null");
        }
        int result = 0;
        try {
            result = tiTrainingMapper.updateNotNullTiTrainingById(value);
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行通过TiTraining的id更新TiTraining中属性不为null的数据-->结果:", result);
        }
        return CommonResult.success(null);
    }

    @Override
    public CommonResult deleteById(Integer id) {
        if (id == null) {
            if (isDebugEnabled) {
                log.debug("执行通过TiTraining的id删除TiTraining-->失败:id不能为空");
            }
            Asserts.fail("执行通过TiTraining的id删除TiTraining-->失败:id不能为空");
        }
        int result = 0;
        try {
            result = tiTrainingMapper.deleteTiTrainingById(id);
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行通过TiTraining的id删除TiTraining-->结果:", result);
        }
        return CommonResult.success(null);
    }


}